package com.tnsw.noxnox.downloader;

import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.http.THttpBase;
import com.tnsw.coreutils.http.THttpGet;
import com.tnsw.coreutils.text.TextUtils;
import com.tnsw.noxnox.db.DBManager;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class DailyMotionDL extends DLBase {

	private String tag = "DailyMotionDL";
	private AsyncManager asyncManager;
	
	private THttpGet httpFirst;
	private THttpGet httpAuto;
	private THttpGet httpContent;
	private THttpGet httpImages;		// For thumbnail
	
	private double duration;
	
	public DailyMotionDL(Context context, String firstUrl) {
		super(context, firstUrl);
		super.dp.video_sites = 2;
				
		this.asyncManager = AsyncManager.getInstance();
		this.httpFirst = new THttpGet(context, firstUrl);
		this.httpFirst.setSessionName("metadata");
		this.httpFirst.addHeader("Accept", "*/*");
		this.httpFirst.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
		this.httpFirst.addHeader("Accept-Encoding", "gzip,deflate,sdch");
		this.httpFirst.addHeader("Accept-Language", "th,en-US;q=0.8,en;q=0.6");
		this.httpFirst.addHeader("Connection", "keep-alive");
		this.httpFirst.addHeader("Cookie", "dmvk=5134c42673365; OAX=tLRRk1E0xCoAAOeV; v1st=2A63CCD56C3D9018; family_filter=off; s_vi=[CS]v1|289A621D852A0631-6000010840046D10[CE]; __utma=244310544.569282931.1362412587.1362412587.1362416223.2; __utmb=244310544.4.9.1362416522860; __utmc=244310544; __utmz=244310544.1362416223.2.2.utmcsr=dailymotion.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmv=244310544.|4=segment=98=1");
		this.httpFirst.addHeader("Host", THttpBase.getHost(firstUrl));
		this.httpFirst.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22");
		
		this.httpFirst.setListener(this);
		
	}
	
	@Override
	public void doit() {
		super.doit();
		
		this.httpFirst.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");
		this.setTextStatus("Downloading meta data..");
	}
	
	/*
	public int indexOfBackward(String str, int startFrom, String s) {
		int ii = -1;
		
		int i = startFrom;
		for (i = startFrom; i >= 0; i--) {
			String ss = str.substring(i, i+s.length());
			if (ss.equals(s)) {
				return(i);
			}
		}
		
		return(ii);
	}
	*/
	
	private void initializeHttpImage(String url) {
		
		this.httpImages = new THttpGet(context, url);
		
		Uri uri = Uri.parse(url);
		if (uri.getLastPathSegment() != null) {
			this.asyncManager.appendNetworkLog("lastPathSegment=" + uri.getLastPathSegment());
			String extension = uri.getLastPathSegment().split("\\.")[1];
			this.httpImages.setPredefinedExtension(extension);
		}
		
		this.httpImages.setSessionName("images");
		this.httpImages.setBinaryDirection(THttpBase.BINARY_TO_FILE);
		this.httpImages.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		this.httpImages.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
		this.httpImages.addHeader("Accept-Encoding", "gzip,deflate,sdch");
		this.httpImages.addHeader("Connection", "keep-alive");
		this.httpImages.addHeader("Accept-Language", "th,en-US;q=0.8,en;q=0.6");
		this.httpImages.addHeader("Host", THttpBase.getHost(url));
		this.httpImages.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4");
		
		this.httpImages.setListener(this);
		this.httpImages.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");		
	}
	
	private void handleMetaData(THttpBase sender, String line) {
		if (line.contains("var flashvars")) {
			sender.stop();
			int idx = line.indexOf("=");
			String jsonStr = line.substring(idx+1, line.length()-1);
			this.asyncManager.appendNetworkLog(jsonStr);
			
			try {
				JSONObject jsObj = new JSONObject(jsonStr);
				Log.d(tag, "jsonStr is OK");
				
				String sequence = jsObj.getString("sequence");
				sequence = URLDecoder.decode(sequence);
				this.asyncManager.appendNetworkLog(sequence);
				
				String stt = TextUtils.getJsonSimpleLevel(sequence, "ldURL");
				this.asyncManager.appendNetworkLog("stt=" + stt);				
				if (stt.equals("") == false) {
					
					JSONObject j2Obj = new JSONObject(stt);
					String ldURL = j2Obj.getString("ldURL");
					String sdURL = j2Obj.getString("sdURL");
					String autoURL = j2Obj.getString("autoURL");
					
					String videoTitleJson = TextUtils.getJsonSimpleLevel(sequence, "videoTitle");
					if (videoTitleJson.equals("") == false) {
						JSONObject j3Obj = new JSONObject(videoTitleJson);
						this.dp.title = j3Obj.getString("videoTitle");
						this.setTitle(this.dp.title);
						Log.d(tag, "Found title=" + this.dp.title);
						
						String videoPreviewURL = "";
						if (j3Obj.has("videoPreviewURL") == true) {
							videoPreviewURL = j3Obj.getString("videoPreviewURL");
							Log.d(tag, "videoPreviewURL=" + videoPreviewURL);
							this.asyncManager.appendNetworkLog("videoPreviewURL=" + videoPreviewURL);
							
							this.initializeHttpImage(videoPreviewURL);
						}
					}
					
					this.asyncManager.appendNetworkLog("ldURL=" + ldURL);
					this.asyncManager.appendNetworkLog("sdURL=" + sdURL);
					this.asyncManager.appendNetworkLog("autoURL=" + autoURL);
					
					this.httpAuto = new THttpGet(this.context, autoURL);
					this.httpAuto.setSessionName("auto");
					this.httpAuto.addHeader("Accept", "*/*");
					this.httpAuto.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
					this.httpAuto.addHeader("Accept-Encoding", "gzip,deflate,sdch");
					this.httpAuto.addHeader("Accept-Language", "th,en-US;q=0.8,en;q=0.6");
					this.httpAuto.addHeader("Connection", "keep-alive");
					this.httpAuto.addHeader("Cookie", "dmvk=5134c42673365; OAX=tLRRk1E0xCoAAOeV; v1st=2A63CCD56C3D9018; family_filter=off; s_vi=[CS]v1|289A621D852A0631-6000010840046D10[CE]; __utma=244310544.569282931.1362412587.1362412587.1362416223.2; __utmb=244310544.4.9.1362416522860; __utmc=244310544; __utmz=244310544.1362416223.2.2.utmcsr=dailymotion.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmv=244310544.|4=segment=98=1");
					this.httpAuto.addHeader("Host", THttpBase.getHost(autoURL));
					this.httpAuto.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22");
					this.httpAuto.setListener(this);
					
					this.httpAuto.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");
					Log.d(tag, "Started download binary..");
				}
			
			} catch (Exception e) {
				Log.e(tag, e.toString(), e);
			}
		}		
	}
	
	
	@Override
	public void onNewLineFetchBG(THttpBase sender, String line) {
		super.onNewLineFetchBG(sender, line);
		
		if (sender == this.httpFirst) {
			this.handleMetaData(sender, line);
		} else if (sender == this.httpAuto) {
			
		}
		
	}
	
	@Override
	public void onPostExecute(THttpBase sender, Long result) {
		super.onPostExecute(sender, result);
		
		if (sender == this.httpFirst) {
			if (this.httpFirst.isStopped() == false) {
				// end with no found of 'var flash'
				Log.w(tag, "Cannot find 'var flashvars'");
				this.asyncManager.appendNetworkLog(this.httpFirst.getCurrentSB().toString());
			}
			if (result == 0) {
				//this.asyncManager.appendNetworkLog(sender.getCurrentSB().toString());
				
			}
			
		} else if (sender == this.httpAuto) {
			Log.d(tag, "urlAUTO, http response=" + sender.getHttpResponse().getStatusLine().getStatusCode());
			
			String str = sender.getCurrentSB().toString();
			this.asyncManager.appendNetworkLog(str);
			
			ArrayList<String> a = new ArrayList<String>();
			try {
				JSONObject json = new JSONObject(str);
				this.duration = json.getDouble("duration");
				this.dp.duration_sec = (int) this.duration;
				JSONArray alternatesJson = json.getJSONArray("alternates");
				int len = alternatesJson.length();
				int i;
				
				for (i = 0; i < len; i++) {
					JSONObject alternateJson = alternatesJson.getJSONObject(i);
					String template = alternateJson.getString("template");
					this.asyncManager.appendNetworkLog("template=" + template);
					
					int width = alternateJson.getInt("width");
					int height = alternateJson.getInt("height");
					String codecs = alternateJson.getString("codecs");
					
					this.hashStdAttrs.put("width", String.valueOf(width));
					this.hashStdAttrs.put("height", String.valueOf(height));
					this.hashStdAttrs.put("codec", codecs);
					
					Uri uri = Uri.parse(template);
					String fileName = uri.getLastPathSegment();
					this.asyncManager.appendNetworkLog("fileName=" + fileName);
					
					String newFileName = fileName.replace(".mnft", ".mp4");
					String binaryUrl = template.replace(fileName, newFileName);
					
					this.asyncManager.appendNetworkLog("binaryUrl=" + binaryUrl);
					a.add(binaryUrl);
				}
				
			} catch (Exception e) {
				Log.e(tag, e.toString(), e);
			}
			
			if (a.size() > 0) {
				String url = a.get(0);
				this.downloadBinary(url);
			}
			
		} else if (sender == this.httpImages) {
			if (sender.getHttpResponse().getStatusLine().getStatusCode() == 200) {
				this.asyncManager.appendNetworkLog("Received thumbnail with HTTP=200");
				String filename = sender.getCurrentBinaryfileName();
				this.dp.thumbnail_filename = filename;
				DBManager dbm = DBManager.getInstance(this.context);
				dbm.updateDownloadProgress(this.dp, true);
			}
		}
		
	}
	
	private void downloadBinary(String url) {
		this.httpContent = new THttpGet(this.context, url);
		this.httpContent.setSessionName("binary");
		this.httpContent.setPredefinedExtension("mp4");
		this.httpContent.setBinaryDirection(THttpBase.BINARY_TO_FILE);
		this.httpContent.addHeader("Accept", "*/*");
		this.httpContent.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
		this.httpContent.addHeader("Accept-Encoding", "gzip,deflate,sdch");
		this.httpContent.addHeader("Accept-Language", "th,en-US;q=0.8,en;q=0.6");
		this.httpContent.addHeader("Connection", "keep-alive");
		this.httpContent.addHeader("Cookie", "dmvk=5134c42673365; OAX=tLRRk1E0xCoAAOeV; v1st=2A63CCD56C3D9018; family_filter=off; s_vi=[CS]v1|289A621D852A0631-6000010840046D10[CE]; __utma=244310544.569282931.1362412587.1362412587.1362416223.2; __utmb=244310544.4.9.1362416522860; __utmc=244310544; __utmz=244310544.1362416223.2.2.utmcsr=dailymotion.com|utmccn=(referral)|utmcmd=referral|utmcct=/; __utmv=244310544.|4=segment=98=1");
		this.httpContent.addHeader("Host", THttpBase.getHost(url));
		this.httpContent.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22");
		this.httpContent.setListener(this);
		
		this.httpContent.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");		
	}
	
	@Override
	public void onProgressUpdate(THttpBase sender, Integer[] values) {
		super.onProgressUpdate(sender, values);
		
		if (super.dlInterface != null) {
			if (sender.getSessionName().equals("binary")) {
				this.setMax(sender.getContentLength());
				this.setCurrentPosition((int) sender.getCurrentPosition());
				
				float percentage = (((float) sender.getCurrentPosition()/ (float) sender.getContentLength())*(float) 100);
				this.setTextStatus(String.valueOf(percentage) + "%");
				
			}
			
			this.dlInterface.onProgressUI(this);
		}
	}
	
	@Override
	public void onReceiveResponseBG(THttpBase sender) {
		super.onReceiveResponseBG(sender);
	}
	
	
	
	

}
